package com.jinmei.remote.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.jinmei.remote.response.JSONResponse;
import com.jinmei.remote.response.ResponseFactory;
import com.jinmei.remote.util.RequestUtils;

public class JERPRequest {
	
	private static final String ENCODING = "UTF-8";
	
	 private HttpClient httpClient;
	 private HttpPost httpRequest;
     private HttpResponse response;
     
     private List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
	
	public void sendRequest(String url) throws Exception {
        httpClient = new DefaultHttpClient();
        httpRequest = new HttpPost(url);
        httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePair));
        response = httpClient.execute(httpRequest);
    }
	
	public <T extends JSONResponse> T getResponse(Class<T> responseClass) throws Exception {
		StringBuilder sb = new StringBuilder();
		int responseCode = response.getStatusLine().getStatusCode();
		
		if (responseCode == 200) {
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            for (String s = bufferedReader.readLine(); s != null; s = bufferedReader
                    .readLine()) {
                sb.append(s);
            }
        }
		
		String responseBody = sb.toString().replace("&lt;", "<").replace("&gt;", ">");
        return ResponseFactory
                .createCustomResponse(responseBody, ENCODING, responseCode, responseClass);
    }
	
	public void addNameValuePair(String key, String value) {
        nameValuePair.add(new BasicNameValuePair(
        		RequestUtils.encode(key, ENCODING), 
        		RequestUtils.encode(value, ENCODING)));
    }
	
}
